package com.ruoyi.blog.controller;


import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.github.pagehelper.PageInfo;
import com.google.zxing.qrcode.encoder.QRCode;
import com.ruoyi.cms.domain.Article;
import com.ruoyi.cms.domain.Category;
import com.ruoyi.cms.domain.Tags;
import com.ruoyi.cms.service.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.IpUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.easywenku.tool.ImageUtil;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;

/**
 * 广告位Controller
 *
 * @author wujiyue
 * @date 2019-11-16
 */
@Controller
@RequestMapping({"/adultexam", "/adultExam", "/"})
public class AdultExamController extends BaseController {
    private static final String prefix = "adultexam";
    //private static final String theme="/pnews";
    //private static final String theme="/pblog";
    //private static final String theme="/avatar";

    @Autowired
    private IArticleService articleService;

    @Autowired
    private AdultService adultService;
    @Autowired
    private ICommentService commentService;

    @Autowired
    private ITagsService tagsService;
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private IResourceService resourceService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ILinkTypeService linkTypeService;
    @Autowired
    private ILinkService linkService;
    @Autowired
    private IBlogThemeService blogThemeService;

    private static LinkedHashMap<String, LinkedHashMap<String, String>> blockArticleMap = new LinkedHashMap<>();

    static {

        blockArticleMap.put("adult", new LinkedHashMap<String, String>() {{
            put("admissionsGuide", "15");
            put("newest", "12");
            put("cheatsForRegistration", "70");
            put("category1", "13");
            put("category2", "14");
            put("category3", "43");
            put("category4", "44");
            put("category5", "45");
            put("category6", "46");
            put("title", "成人高考-成考");
            put("pid", "11");

        }});
        blockArticleMap.put("network", new LinkedHashMap<String, String>() {{
            put("admissionsGuide", "20");
            put("newest", "17");
            put("cheatsForRegistration", "71");
            put("category1", "18");
            put("category2", "19");
            put("category3", "48");
            put("category4", "49");
            put("category5", "50");
            put("category6", "51");
            put("title", "网络教育");
            put("pid", "16");

        }});
        blockArticleMap.put("unifiedRecruitment", new LinkedHashMap<String, String>() {{
            put("admissionsGuide", "25");
            put("newest", "22");
            put("cheatsForRegistration", "72");

            put("category1", "23");
            put("category2", "24");
            put("category3", "52");
            put("category4", "53");
            put("category5", "54");
            put("category6", "55");
            put("title", "统招专升本");
            put("pid", "21");

        }});
        blockArticleMap.put("openUniversity", new LinkedHashMap<String, String>() {{
            put("admissionsGuide", "30");
            put("newest", "27");
            put("cheatsForRegistration", "73");

            put("category1", "28");
            put("category2", "29");
            put("category3", "57");
            put("category4", "58");
            put("category5", "59");
            put("category6", "60");
            put("title", "国家开放大学");
            put("pid", "26");

        }});
        blockArticleMap.put("vocationalEducation", new LinkedHashMap<String, String>() {{
            put("admissionsGuide", "35");
            put("newest", "32");
            put("cheatsForRegistration", "74");

            put("category1", "33");
            put("category2", "34");
            put("category3", "61");
            put("category4", "62");
            put("category5", "63");
            put("category6", "64");
            put("title", "职业教育");
            put("pid", "31");

        }});
        blockArticleMap.put("postgraduate", new LinkedHashMap<String, String>() {{
            put("admissionsGuide", "40");
            put("newest", "37");
            put("cheatsForRegistration", "75");

            put("category1", "38");
            put("category2", "39");
            put("category3", "65");
            put("category4", "66");
            put("category5", "67");
            put("category6", "68");
            put("title", "在职研究生");
            put("pid", "36");

        }});
    }

    public static Cache<String, Integer> articleViewCache = CacheUtil.newLRUCache(1000, 1000 * 60 * 60);
    public static Cache<String, Integer> articleUpVoteCache = CacheUtil.newLRUCache(1000, 1000 * 60 * 60);
    public static Cache<String, Integer> commentUpVoteCache = CacheUtil.newLRUCache(1000, 1000 * 60 * 60);
    public static Cache<String, Map> bannerCache = CacheUtil.newTimedCache(1000 * 60 * 60);

    public static Cache<String, Object> blogCache = CacheUtil.newTimedCache(1000 * 60 * 60);

    private String getTheme() {
        return "";
    }

    /**
     * 首页
     *
     * @param model
     * @return
     */
    @GetMapping({"/", "", "/index"})
    public String index(Model model) {

        return prefix + "/index";
    }

    /**
     * 成人教育
     *
     * @param model
     * @return
     */
    @GetMapping({"/{blockType:adult|network}"})
    public String adult(Model model, @PathVariable("blockType") String blockType) {

        LinkedHashMap<String, String> category = blockArticleMap.get(blockType);
        if (category == null) {
            return blockType;
        }
        model.addAttribute("title", category.get("title"));

        String[] keys = category.keySet().toArray(new String[category.size()]);


        List<Article> articleshotNewest = adultService.ArticleByCategPage(category.get(keys[1]), 1, "hot", 7);
        model.addAttribute("hotNewest", articleshotNewest);

        ArrayList<Object> returnArticle = new ArrayList<>();

        // 三个栏目组成块
        List<List<Article>> articless = new ArrayList<>();
        List<String> categoryNames = new ArrayList<>();

        for (int i = 0; i < keys.length; i++) {
            String s = keys[i];
            if ("title".equals(s)) {
                continue;
            }
            if (articless.size() >= 3) {
                HashMap<String, List> hashMap = new HashMap<>();
                hashMap.put("articless", articless);
                hashMap.put("categoryNames", categoryNames);
                returnArticle.add(hashMap);
                articless = new ArrayList<>();
                categoryNames = new ArrayList<>();
            }
            List<Article> articles = adultService.ArticleByCategPage(category.get(s), 1, 7);
            String categoryName = categoryService.selectCategoryById(Long.parseLong(category.get(s))).getCategoryName();
            if (i <= 2) {
                model.addAttribute(s, articles);
                continue;
            }
            if (articles.size() > 0) {
                articless.add(articles);
            }
            categoryNames.add(categoryName);
        }
        if (!articless.isEmpty()) {
            HashMap<String, List> hashMap = new HashMap<>();
            hashMap.put("articless", articless);
            hashMap.put("categoryNames", categoryNames);
            returnArticle.add(hashMap);
        }

        model.addAttribute("blockType", blockType);
        model.addAttribute("returnArticle", returnArticle);

        Category pid = categoryService.selectCategoryById(Long.parseLong(category.get("pid")));

        model.addAttribute("category", pid);

        return prefix + "/block";
    }


    /**
     * 文章详情
     *
     * @param model
     * @param articleId
     * @return
     */
    @GetMapping("/article/{articleId}")
    public String article(HttpServletRequest request, Model model, @PathVariable("articleId") String articleId) {
        Article article = articleService.selectArticleById(articleId);


        List<Article> applicationCheats = (List<Article>) blogCache.get("applicationCheats");
        if (applicationCheats == null) {
            applicationCheats = adultService.ArticleByCategPage("70", 1, 7);
            applicationCheats.addAll(adultService.ArticleByCategPage("71", 1, 7));
            applicationCheats.addAll(adultService.ArticleByCategPage("72", 1, 7));
            applicationCheats.addAll(adultService.ArticleByCategPage("73", 1, 7));
            applicationCheats.addAll(adultService.ArticleByCategPage("74", 1, 7));
            applicationCheats.addAll(adultService.ArticleByCategPage("75", 1, 7));
            blogCache.put("applicationCheats", applicationCheats);
        }

        List<Article> latestTestQuestions = (List<Article>) blogCache.get("latestTestQuestions");
        if (latestTestQuestions == null) {
            latestTestQuestions = adultService.ArticleByCategPage("44", 1, 7);
            latestTestQuestions.addAll(adultService.ArticleByCategPage("49", 1, 7));
            latestTestQuestions.addAll(adultService.ArticleByCategPage("53", 1, 7));
            latestTestQuestions.addAll(adultService.ArticleByCategPage("58", 1, 7));
            latestTestQuestions.addAll(adultService.ArticleByCategPage("62", 1, 7));
            latestTestQuestions.addAll(adultService.ArticleByCategPage("66", 1, 7));
            blogCache.put("latestTestQuestions", latestTestQuestions);
        }


        if (article == null) {
            throw new BusinessException("该文章不存在!");
        }
        articleService.articleLook(articleId);
        model.addAttribute("article", article);
        model.addAttribute("latestTestQuestions", latestTestQuestions);
        model.addAttribute("applicationCheats", applicationCheats);
        return prefix + "/details";
    }

    /**
     * 分类列表
     *
     * @param model
     * @return
     */
    @GetMapping("/category")
    public String category(Model model) {
        model.addAttribute("categoryId", "category");
        Article form = new Article();
        startPage();
        List<Article> articles = articleService.selectArticleList(form);
        PageInfo pageInfo = new PageInfo(articles);
        model.addAttribute("total", pageInfo.getTotal());
        model.addAttribute("pageNo", pageInfo.getPageNum());
        model.addAttribute("pageSize", pageInfo.getPageSize());
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("hasPrevious", pageInfo.isHasPreviousPage());
        model.addAttribute("hasNext", pageInfo.isHasNextPage());
        model.addAttribute("currentPage", pageInfo.getPageNum());
        model.addAttribute("prePage", pageInfo.getPrePage());
        model.addAttribute("nextPage", pageInfo.getNextPage());
        model.addAttribute("navNums", pageInfo.getNavigatepageNums());
        model.addAttribute("articleList", articles);
        return prefix + "/" + getTheme() + "/category_article";
    }

    /**
     * 分类文章列表
     *
     * @param categoryId
     * @param model
     * @return
     */
    @GetMapping("/category/{categoryId}")
    public String categoryBy(@PathVariable("categoryId") String categoryId, Model model) {
        Category category = categoryService.selectCategoryById(Long.valueOf(categoryId));

        if (category != null) {

            model.addAttribute("category", category);

        }
        Article form = new Article();
        form.setCategoryId(categoryId);
        model.addAttribute("categoryId", categoryId);
        startPage(1, 20);
        // startPage();
        List<Article> articles = articleService.selectArticleList(form);
        PageInfo pageInfo = new PageInfo(articles);
        model.addAttribute("total", pageInfo.getTotal());
        model.addAttribute("pageNo", pageInfo.getPageNum());
        model.addAttribute("pageSize", pageInfo.getPageSize());
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("hasPrevious", pageInfo.isHasPreviousPage());
        model.addAttribute("hasNext", pageInfo.isHasNextPage());
        model.addAttribute("currentPage", pageInfo.getPageNum());
        model.addAttribute("prePage", pageInfo.getPrePage());
        model.addAttribute("nextPage", pageInfo.getNextPage());
        model.addAttribute("navNums", pageInfo.getNavigatepageNums());
        model.addAttribute("articleList", articles);




        List<Article> applicationCheats = (List<Article>) blogCache.get("applicationCheats");
        if (applicationCheats == null) {
            applicationCheats = adultService.ArticleByCategPage("70", 1, 7);
            applicationCheats.addAll(adultService.ArticleByCategPage("71", 1, 7));
            applicationCheats.addAll(adultService.ArticleByCategPage("72", 1, 7));
            applicationCheats.addAll(adultService.ArticleByCategPage("73", 1, 7));
            applicationCheats.addAll(adultService.ArticleByCategPage("74", 1, 7));
            applicationCheats.addAll(adultService.ArticleByCategPage("75", 1, 7));
            blogCache.put("applicationCheats", applicationCheats);
        }

        List<Article> latestTestQuestions = (List<Article>) blogCache.get("latestTestQuestions");
        if (latestTestQuestions == null) {
            latestTestQuestions = adultService.ArticleByCategPage("44", 1, 7);
            latestTestQuestions.addAll(adultService.ArticleByCategPage("49", 1, 7));
            latestTestQuestions.addAll(adultService.ArticleByCategPage("53", 1, 7));
            latestTestQuestions.addAll(adultService.ArticleByCategPage("58", 1, 7));
            latestTestQuestions.addAll(adultService.ArticleByCategPage("62", 1, 7));
            latestTestQuestions.addAll(adultService.ArticleByCategPage("66", 1, 7));
            blogCache.put("latestTestQuestions", latestTestQuestions);
        }

        model.addAttribute("latestTestQuestions", latestTestQuestions);
        model.addAttribute("applicationCheats", applicationCheats);
        return prefix + "/list";
    }


    /**
     * 搜索内容
     * 目前仅支持文章标题模糊搜索
     *
     * @param content
     * @param model
     * @return
     */
    @GetMapping("/search")
    public String search(String content, Model model) {
        model.addAttribute("content", content);
        Article form = new Article();
        form.setTitle(content.trim());
        startPage();
        List<Article> articles = articleService.selectArticleList(form);
        PageInfo pageInfo = new PageInfo(articles);
        model.addAttribute("total", pageInfo.getTotal());
        model.addAttribute("pageNo", pageInfo.getPageNum());
        model.addAttribute("pageSize", pageInfo.getPageSize());
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("hasPrevious", pageInfo.isHasPreviousPage());
        model.addAttribute("hasNext", pageInfo.isHasNextPage());
        model.addAttribute("currentPage", pageInfo.getPageNum());
        model.addAttribute("prePage", pageInfo.getPrePage());
        model.addAttribute("nextPage", pageInfo.getNextPage());
        model.addAttribute("navNums", pageInfo.getNavigatepageNums());
        model.addAttribute("articleList", articles);
        return prefix + "/" + getTheme() + "/search";
    }

    /**
     * 标签列表
     *
     * @param tagId
     * @param model
     * @return
     */
    @GetMapping("/tag/{tagId}")
    public String tag(@PathVariable("tagId") String tagId, Model model) {
        model.addAttribute("tagId", tagId);
        Tags tag = tagsService.selectTagsById(Long.valueOf(tagId));
        if (tag != null) {
            model.addAttribute("tagName", tag.getTagName());
        }
        Article form = new Article();
        form.setTag(tagId);
        model.addAttribute("pageUrl", "blog/tag/" + tagId);
        startPage();
        List<Article> articles = articleService.selectArticleList(form);
        PageInfo pageInfo = new PageInfo(articles);
        model.addAttribute("total", pageInfo.getTotal());
        model.addAttribute("pageNo", pageInfo.getPageNum());
        model.addAttribute("pageSize", pageInfo.getPageSize());
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("hasPrevious", pageInfo.isHasPreviousPage());
        model.addAttribute("hasNext", pageInfo.isHasNextPage());
        model.addAttribute("currentPage", pageInfo.getPageNum());
        model.addAttribute("prePage", pageInfo.getPrePage());
        model.addAttribute("nextPage", pageInfo.getNextPage());
        model.addAttribute("navNums", pageInfo.getNavigatepageNums());
        model.addAttribute("articleList", articles);
        return prefix + "/" + getTheme() + "/tag";
    }


    @PostMapping("/article/upVote")
    @ResponseBody
    public AjaxResult articleUpVote(HttpServletRequest request, String articleId) {
        if (StringUtils.isEmpty(articleId)) {
            return AjaxResult.error("系统错误!");
        }
        String ip = IpUtils.getIpAddr(request);
        Integer n = articleUpVoteCache.get(ip + "|" + articleId);
        if (n == null || n == 0) {
            articleService.upVote(articleId);
            articleUpVoteCache.put(ip + "|" + articleId, 1);
            return AjaxResult.success("点赞数+1");
        } else {
            articleUpVoteCache.put(ip + "|" + articleId, n++);
            return AjaxResult.error("系统错误!");
        }
    }


    /**
     * 分享图片
     *
     * @param
     * @return
     */
    @GetMapping({"/shareImage/{id}"})
    public void image(HttpServletResponse response, @PathVariable("id") String id) {


        Article byId = articleService.getById(id);
        String title = "文章未找到";
        String text = "";
        if (null != byId) {
            title = byId.getTitle();
            text = byId.getDescription();
            if (text==null) {
                text="摘要为空";
            }
        }
        response.setContentType("image/jpeg");
        response.setDateHeader("expries", -1);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        BufferedImage notice = ImageUtil.overlapImage(title, text,"https://www.easywk.cn/article/"+id);
        try {
            ServletOutputStream outputStream = response.getOutputStream();

            ImageIO.write(notice, "jpg", outputStream);
            outputStream.flush();
            outputStream.close();
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
